import tinymce from 'tinymce/tinymce'
import { getRange } from '@/utils/helpers'
import { addComment, fetchComments } from '@/api'
import store from '@/store'

tinymce.PluginManager.add('comment', function (editor) {
  // 添加修改批注
  const openDialog = function () {
    return tinymce.activeEditor.windowManager.open({
      title: `请输入批注内容`,
      size: 'normal',
      body: {
        type: "panel",
        items: [{ type: "input", name: "content", label: "" }]
      },
      buttons: [
        { type: 'cancel', name: 'cancel', text: '取消' },
        { type: 'submit', name: 'save', text: '确定', primary: true }
      ],
      initialData: {
        content: ""
      },
      async onSubmit(e) {
        const { content } = e.getData()
        if (!content || !content.trim()) {
          Message.warning('请输入内容')
          return
        }

        const range = getRange()
        const docNo = store.state.xmleditor.editorConfig.docNo
        await addComment({ content, docNo, ...range })
        await fetchComments()
        tinymce.activeEditor.notificationManager.open({
          timeout: 1500,
          text: '保存成功!',
          type: 'success'
        })
        e.close()
      }
    })
  }

  return (
    editor.ui.registry.addMenuButton('comment', {
      tooltip: '批注',
      icon: 'comment',
      fetch(callback) {
        callback([
          {
            type: 'menuitem',
            text: '添加批注',
            onAction() {
              const docContent = editor.selection.getContent({ format: 'text' })
              if (!docContent) {
                // 必须选中文字才可以添加批注
                editor.windowManager.alert("未选中内容")
                return
              }
              openDialog()
            }
          },
          {
            type: 'menuitem',
            text: '查看批注',
            async onAction() {
              store.commit('xmleditor/CHANGE_SIDEBAR_ACTIVE_NAV', { side: 'right', activeNav: 'Comment' })
              store.commit('xmleditor/CHANGE_SIDEBAR_ACTIVE_COLLAPSE', { side: 'right', collapse: false })
              await fetchComments()
            }
          }
        ])
      }
    }),
    {
      getMetadata() {
        return {
          name: '批注',
          url: 'http://sfrj.cn'
        }
      }
    }
  )
})
